package com.itheima.crm.service.imp;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.crm.dao.ICustomerRepository;
import com.itheima.crm.domain.Customer;
import com.itheima.crm.service.ICustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements ICustomerService {

	// 注入dao
	@Autowired
	private ICustomerRepository customerRepository;

	@Override
	public List<Customer> findNoAssociationCustomer() {
		// fixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findAssociationFixedAreaCustomers(String fixedAreaId) {

		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomerToFixedArea(String customerIdStr,
			String fixedAreaId) {
		// 接触关联动作
		customerRepository.clearFixedAreaId(fixedAreaId);

		// 判断customerIdStr是否为null
		if ("null".equals(customerIdStr)) {
			return;
		}

		// 如果customerIdStr为空直接结束方法
		if (StringUtils.isBlank(customerIdStr)) {
			return;
		}

		String[] idCustomerArray = customerIdStr.split(",");
		for (String idStr : idCustomerArray) {
			Integer id = Integer.parseInt(idStr);
			customerRepository.updateFixedAreaId(fixedAreaId, id);
		}
	}

	// 客户注册
	@Override
	public void regist(Customer customer) {
		customerRepository.save(customer);
	}

	// 查询客户信息，根据手机号
	@Override
	public Customer findByTelephone(String telephone) {

		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}
	
	//客户登录
	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}
	
	//完全匹配定区
	@Override
	public String findfixedAreaIdByAddress(String address) {
		
		return customerRepository.findfixedAreaIdByAddress(address);
	}

}
